package com.wx.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;


@ConfigurationProperties(prefix = "ribbon.direct-servers")
public class DirectRule extends AbstractLoadBalancerRule {

    private final static Logger logger = LoggerFactory.getLogger(DirectRule.class);

    private String hostPort = "";

    public String getHostPort() {
        return hostPort;
    }

    public void setHostPort(String hostPort) {
        if (!StringUtils.hasText(hostPort)) {
            throw new IllegalArgumentException("hostPort is null");
        }
        this.hostPort = hostPort;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {
        return chooseServer(getLoadBalancer(), key);
    }

    private Server chooseServer(ILoadBalancer lb, Object key) {
        if (lb == null) {
            logger.warn("no load balancer");
            return null;
        }

        Server server = null;
        int count = 0;
        while (server == null && count++ < 10) {
            List<Server> reachableServers = lb.getReachableServers();
            List<Server> allServers = lb.getAllServers();
            int upCount = reachableServers.size();
            int serverCount = allServers.size();

            if ((upCount == 0) || (serverCount == 0)) {
                logger.warn("no up servers available from load balancer: " + lb);
                return null;
            }

            server = targetServer();

            if (server == null) {
                /* Transient. */
                Thread.yield();
                continue;
            }

            if (server.isAlive() && (server.isReadyToServe())) {
                return (server);
            }

            // Next.
            server = null;
        }

        if (count >= 10) {
            logger.warn("no available alive servers after 10 tries from load balancer: " + lb);
        }
        return server;
    }

    private Server targetServer() {
        List<Server> serverList = getLoadBalancer().getAllServers().stream().filter(el -> el.getHostPort().equalsIgnoreCase(hostPort)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(serverList)) {
            return serverList.get(0);
        }
        logger.warn("no appoint balancer");
        return null;
    }
}
